
#include "iphonewindow.h"
#include <QMouseEvent>
#include <QPushButton>
#include <QPainter>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include "custombutton.h"
#include "bottomall.h"
#include "contentarea.h"
#include "shopunit.h"
#include "topsidebar.h"
#include <QCoreApplication>
#include <QLabel>
#include <QTimer>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMessageBox>
#include "qcustombutton.h"
#include "postreply.h"
#include <QListWidget>
#include <QString>
#include <QInputDialog>
#include <QLabel>
#include <QMainWindow>


IphoneWindow::IphoneWindow(QWidget *parent)
    : QWidget(parent)
    //m_postList(new QListWidget(this))
{

    setWindowFlags(Qt::FramelessWindowHint); // 设置窗口无边框

    // 设置窗口尺寸

    this->setFixedSize(390, 800);
    loadMenuButtons();

}

    // 重写绘制窗口边框的事件
void IphoneWindow::paintEvent(QPaintEvent *event) /*override*/ {
    QWidget::paintEvent(event);

    // 使用 QPainter 绘制窗口边框
    QPainter painter(this);
    painter.setPen(Qt::white);
    painter.drawRect(rect().adjusted(0, 0, -1, -1));


}

    // 重写鼠标按下事件，用于拖动窗口
void IphoneWindow::mousePressEvent(QMouseEvent *event) /*override*/ {
    if (event->button() == Qt::LeftButton) {
        // 记录当前鼠标位置和窗口位置，用于计算偏移量
        MDragStartPosition = event->globalPos();
        MDragWindowPosition = frameGeometry().topLeft();
    }

    QWidget::mousePressEvent(event);
}

    // 重写鼠标移动事件，用于拖动窗口
void IphoneWindow::mouseMoveEvent(QMouseEvent *event) /*override*/ {
    if (event->buttons() & Qt::LeftButton) {
        // 计算鼠标的偏移量，根据偏移量移动窗口位置
        QPoint DragDelta = event->globalPos() - MDragStartPosition;
        move(MDragWindowPosition + DragDelta);
    }

    QWidget::mouseMoveEvent(event);
}


    // 首页加载
void IphoneWindow::StartHomePage() {

    //this->DeleteAll();
    int childCount = this->findChildren<QWidget *>().count();
    qDebug()<<"childcount:"<<childCount<<"\n";
    if(childCount)DeleteAll();

    // 底边栏位置（0，700）->(390, 800)
    BottomAll *homeBSbar = new BottomAll(this);
    connect(homeBSbar->BSbar->homeButton, &CustomButton::clicked, this, &IphoneWindow::StartHomePage);
    connect(homeBSbar->BSbar->forumButton, &CustomButton::clicked, this, &IphoneWindow::StartPost);
    homeBSbar->raise();
    homeBSbar->show();

    //顶部栏位置（0，0）->(390, 70)
    TopSidebar *TSbar = new TopSidebar(this);
    TSbar->stackUnder(this->MenuButtons);
    //TSbar->move(50, 0);
    TSbar->show();

    // 滑动区域添加
    ContentArea *contents = new ContentArea(this);
    contents->stackUnder(TSbar);
    contents->show();

    // 添加商铺
    for(int  i= 1; i <= 8; i++) {
        ShopUnit *shop = new ShopUnit(contents);
        contents->VLayout->addWidget(shop);
    }

    this->setWindowTitle("高校社区消费交流体验平台");
    //this->show();

//BottomAll *BSbar = new BottomAll(this);

    //m_postList->setFixedSize(390,670);

}

void IphoneWindow::StartPost() {

    //this->DeleteAll();
    int childCount = this->findChildren<QWidget *>().count();
    qDebug()<<"childcount:"<<childCount<<"\n";
    if(childCount)DeleteAll();

    //QWidget *temp = new QWidget(this);
    m_postList = new QListWidget(this);
    m_postList->setAutoFillBackground(true);
    m_postList->setStyleSheet("background-color: transparent;"
                  "border: 1px solid transparent;"
                  "border-radius: 20px;");
    m_postList->show();
    //m_postList->move(10000, 10000);



    // 底边栏位置（0，700）->(390, 800)
    BottomAll *homeBSbar = new BottomAll(this);
    connect(homeBSbar->BSbar->homeButton, &CustomButton::clicked, this, &IphoneWindow::StartHomePage);
    connect(homeBSbar->BSbar->forumButton, &CustomButton::clicked, this, &IphoneWindow::StartPost);
    homeBSbar->raise();
    homeBSbar->show();

    //顶部栏位置（0，0）->(390, 70)
    TopSidebar *TSbar = new TopSidebar(this);
    TSbar->stackUnder(this->MenuButtons);
    //TSbar->move(50, 0);
    TSbar->show();

    QVBoxLayout *layout = new QVBoxLayout(this);
    m_postList->stackUnder(homeBSbar);
    m_postList->move(5,75);
    m_postList->setFixedSize(380, 400);
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    QPushButton *btn1 = new QPushButton("好评如潮榜", this);
    btn1->setStyleSheet("background-color: #f5bd55;");
    QPushButton *btn2 = new QPushButton("褒贬不一帮", this);
    QPushButton *btn3 = new QPushButton("亟待改正帮", this);
    QPushButton *btn4 = new QPushButton("1.今日好评榜第一                             好评度：999", this);
    QPushButton *btn5 = new QPushButton("2.今日好评榜第二                               好评度：99", this);
    QPushButton *btn6 = new QPushButton("3.今日好评榜第三                                 好评度：9", this);
    btn1->setFixedSize(100, 40);
    btn1->move(40, 460);
    btn1->show();
    //layout->addWidget(btn1);
    btn2->resize(100, 40);
    btn2->move(140, 460);
    btn2->show();
    btn3->resize(100, 40);
    btn3->move(240, 460);
    btn3->show();
    btn4->resize(300, 40);
    btn4->move(40, 500);
    btn4->show();
    btn5->resize(300, 40);
    btn5->move(40, 540);
    btn5->show();
    btn6->resize(300, 40);
    btn6->move(40, 580);
    btn6->show();

    QPushButton *btn7 = new QPushButton(this);
    QPushButton *btn8 = new QPushButton(this);
    QPushButton *btn9 = new QPushButton(this);
    QPushButton *btn10 = new QPushButton(this);
    QPushButton *btn11 = new QPushButton(this);
    btn7->setIcon(QIcon(":res/UI/1.png"));
    btn7->resize(60, 50);
    btn7->move(40, 620);
    btn7->show();
    btn8->setIcon(QIcon(":res/UI/2.png"));
    btn8->resize(60, 50);
    btn8->move(100, 620);
    btn8->show();
    btn9->setIcon(QIcon(":res/UI/3.png"));
    btn9->resize(60, 50);
    btn9->move(160, 620);
    btn9->show();
    btn10->setIcon(QIcon(":res/UI/4.png"));
    btn10->resize(60, 50);
    btn10->move(220, 620);
    btn10->show();
    btn11->setIcon(QIcon(":res/UI/5.png"));
    btn11->resize(60, 50);
    btn11->move(280, 620);
    btn11->show();


// 设置 QListWidget 的显示模式和其他属性
    m_postList->setViewMode(QListView::IconMode);
    m_postList->setIconSize(QSize(50, 50));
    m_postList->setWordWrap(true);
    mainLayout->addWidget(m_postList);

    // 创建按钮，用于添加帖子
    QPushButton *addButton = new QPushButton("发帖", this);
    addButton->resize(390,20);
    addButton->move(0,680);
    addButton->show();
//    layout->addWidget(addButton);

    // 添加帖子输入框
    QLineEdit *postInput = new QLineEdit(this);
    postInput->setPlaceholderText("请输入帖子内容...");
    postInput->resize(390,20);
    postInput->move(0,660);
    postInput->show();
//    layout->addWidget(postInput);

//    // 设置垂直布局的对齐方式为底部对齐
//    layout->setAlignment(Qt::AlignBottom);

//    // 将垂直布局添加到主布局
//    mainLayout->setSpacing(0);

//    // 设置主布局的间距和边距
//    mainLayout->setSpacing(0);
//    mainLayout->setContentsMargins(0, 75, 0, 100);
//    //m_postList->show();

    connect(addButton, &QPushButton::clicked, this, &IphoneWindow::addPost);
}

void IphoneWindow::DeleteAll() {


    // 删除所有子控件
    QList<QWidget*> childWidgets = this->findChildren<QWidget*>();
    foreach (QWidget* childWidget, childWidgets) {

        childWidget->deleteLater();
    }

    // 延迟调用添加新子控件的操作
    QTimer::singleShot(0, this, &IphoneWindow::loadMenuButtons);

}

void IphoneWindow::addPost()
{
    // 从 QLineEdit 中获取帖子内容
        QLineEdit *postInput = findChild<QLineEdit *>();
    if (!postInput)
        return;

    QString postContent = postInput->text();
    if (postContent.isEmpty()) {
        return;
    }

    // 创建一个 Post 对象，并将其添加到 QListWidget 中
    QDateTime postTime = QDateTime::currentDateTime();
    Post *post = new Post(postContent, postTime);
    QListWidgetItem *item = new QListWidgetItem(QIcon(":/icon.png"), post->content(), m_postList);
    item->setData(Qt::UserRole, QVariant::fromValue(post));
    m_postList->addItem(item);

    // 添加回复按钮，用于显示和添加回复
    QPushButton *replyButton = new QPushButton("回复", m_postList);
    replyButton->setStyleSheet("border:none;color:blue;text-decoration:underline;");
    replyButton->setProperty("post", QVariant::fromValue(post));
    connect(replyButton, &QPushButton::clicked, [=]() { replyPost(post); });

    // 添加一个 QCustomButton，并将其附加到 QListWidgetItem 上
    QCustomButton *likeButton = new QCustomButton(m_postList->count() - 1, m_postList);
    likeButton->setIcon(QIcon(":/unliked.png"));
    likeButton->setFixedSize(QSize(300, 50));
    likeButton->setStyleSheet("border:none;");
    connect(likeButton, &QPushButton::clicked, [=]() { likePost(post); });
    replyButton->setMinimumWidth(likeButton->sizeHint().width());
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(likeButton);
    buttonLayout->addWidget(replyButton, 0, Qt::AlignRight);
    buttonLayout->setContentsMargins(0, 0, 0, 0);

    // 创建一个 QVBoxLayout，用于将帖子项和回复按钮布局在一起
    QVBoxLayout *postLayout = new QVBoxLayout();
    QLabel *contentLabel = new QLabel(postContent);
    contentLabel->setWordWrap(true);
    contentLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop); // 设置对齐方式
    //postLayout->addWidget(contentLabel);
    postLayout->addLayout(buttonLayout);

    QWidget *postWidget = new QWidget(m_postList);
    postWidget->setLayout(postLayout);
    item->setSizeHint(postWidget->sizeHint());
    m_postList->setItemWidget(item, postWidget);

    // 清空 QLineEdit 中的内容
    postInput->clear();
}

void IphoneWindow::likePost(Post *post)
{
    QListWidgetItem *item = nullptr;
    for (int i = 0; i < m_postList->count(); i++) {
        QListWidgetItem *currentItem = m_postList->item(i);
        Post *currentPost = currentItem->data(Qt::UserRole).value<Post *>();
        if (currentPost == post) {
            item = currentItem;
            break;
        }
    }

    if (!item)
        return;

    post->addLike();

    QString postInfo = QString("%1\n发帖时间：%2\n点赞数：%3\n%4个回复").arg(post->content()).arg(post->time().toString("yyyy-MM-dd hh:mm:ss")).arg(post->likeCount()).arg(post->replies().count());
                                                                                                                                                                                           item->setToolTip(postInfo);
}

void IphoneWindow::replyPost(Post *post)
{
bool ok = false;
    QString replyContent = QInputDialog::getText(this, "回复帖子", "请输入回复内容：", QLineEdit::Normal, "", &ok);
    if (!ok) {
        return;
    }

    QDateTime replyTime = QDateTime::currentDateTime();
    PostReply *reply = new PostReply(replyContent, replyTime);
    post->addReply(reply);

    QListWidgetItem *item = nullptr;
    for (int i = 0; i < m_postList->count(); i++) {
        QListWidgetItem *currentItem = m_postList->item(i);
        Post *currentPost = currentItem->data(Qt::UserRole).value<Post *>();
        if (currentPost == post) {
            item = currentItem;
            break;
        }
    }

    if (!item)
        return;

    QString postInfo = QString("%1\n发帖时间：%2\n点赞数：%3\n%4个回复").arg(post->content()).arg(post->time().toString("yyyy-MM-dd hh:mm:ss")).arg(post->likeCount()).arg(post->replies().count());
    item->setToolTip(postInfo);
}


void IphoneWindow::loadMenuButtons() {

    MenuButtons = new QWidget(this);
    MenuButtons->setFixedSize(80, 20);
    MenuButtons->move(315, 0);


    // 关闭按钮
    CustomButton *CloseButton = new CustomButton(MenuButtons);
    CloseButton->setIcon(QIcon(":/res/UI/close.png"));
    connect(CloseButton, &CustomButton::clicked, this, &IphoneWindow::close);
    CloseButton->resize(18, 18);
    //CloseButton->move(360, 3);

    // 最小化按钮
    CustomButton *MinsizeButton = new CustomButton(MenuButtons);
    MinsizeButton->setIcon(QIcon(":/res/UI/min.png"));
    connect(MinsizeButton, &CustomButton::clicked, this, &IphoneWindow::showMinimized);
    MinsizeButton->resize(18, 18);
    //MinsizeButton->move(330, 3);

    // 水平按钮分组
    QHBoxLayout *HLayout = new QHBoxLayout(MenuButtons);
    MenuButtons->setLayout(HLayout);
    HLayout->addWidget(MinsizeButton);
    HLayout->addWidget(CloseButton);
    HLayout->setAlignment(Qt::AlignRight | Qt::AlignTop);
    HLayout->setSizeConstraint(QLayout::SetFixedSize);

    // 顶置、fixedcelue、设置布局
    MenuButtons->move(315, 0);
    MenuButtons->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    MenuButtons->raise();
    qDebug()<<"what's wrong?";

    MenuButtons->show();

}
